<template>
  <div class="user">
    <!-- 顶部 -->
    <van-row @click="showLoginModel">
      <van-col span="6">
        <img :src="avatarSrc" alt />
      </van-col>
      <van-col span="14">{{ nickname }}</van-col>
      <van-col span="4">
        <van-icon :name="iconName" @click.stop="toShowLogoutModel"/>
      </van-col>
    </van-row>

    <!-- 底部宫格 -->
    <van-grid :column-num="3">
      <van-grid-item
        v-for="item,index in gridList"
        :key="index"
        :icon="item.iconName"
        :text="item.text"
      />
    </van-grid>

    <!-- 弹出层 -->
    <transition name="van-fade">
      <van-popup v-model="isShowLoginModel">
        <van-form @submit="onSubmit">
          <van-field
            v-model="username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="pwd"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <div style="margin: 16px">
            <van-button round block type="danger" native-type="submit"
              >提交</van-button
            >
          </div>
        </van-form>
      </van-popup>
    </transition>
  </div>
</template>

<script>
import avatarSrc from "../assets/user/avatar.png";
// 请求api相关
import { loginByWeb } from "@/request/loginApi.js";

// vuex
import { mapMutations, mapState } from 'vuex'
export default {
  components: {},
  data() {
    return {
      avatarSrc,
      nickname: "点击登录",
      iconName:'arrow', // 名称右侧的图标，未登录时是arrow 登陆成功后要切换成 cross
      isShowLoginModel: false,  //是否弹出登录框
      username: "",
      password: "",
      gridList:[
        {
            iconName:'label-o',
            text:'我的订单'
        },
        {
            iconName:'bill-o',
            text:'优惠卷'
        },
        {
            iconName:'goods-collect-o',
            text:'礼品卡'
        },
        {
            iconName:'location-o',
            text:'我的收藏'
        },
        {
            iconName:'flag-o',
            text:'我的足迹'
        },
        {
            iconName:'vip-card-o',
            text:'会员福利'
        },
        {
            iconName:'aim',
            text:'地址管理'
        },
        {
            iconName:'warn-o',
            text:'账号安全'
        },
        {
            iconName:'service-o',
            text:'联系客服'
        },
        {
            iconName:'question-o',
            text:'帮助中心'
        },
        {
            iconName:'smile-o',
            text:'意见反馈'
        },
      ]
    };
  },
  computed:{
    ...mapState({
      isGoBack: state => state.isGoBack.isGoBack
    })
  },
  created(){
      let token = localStorage.getItem('token')
      if(token){
            let userInfo = JSON.parse(localStorage.getItem('userInfo')) 
            this.avatarSrc = userInfo.avatar
            this.nickname = userInfo.nickname
            this.iconName = 'cross'
      }
  },
  methods: {
    ...mapMutations({
      chanIsGoBack:'isGoBack/chanIsGoBack'
    }),
    // 打开登录弹窗
    showLoginModel() {
        let token = localStorage.getItem('token')
        if(token){
            return
        }
        this.isShowLoginModel = !this.isShowLoginModel;
    },
    // 提交表单（登录）
    onSubmit(values) {
      // values直接涵盖了表单的所有内容，并且是一个对象值
      loginByWeb(values).then((res) => {
        if (res.errno == 0) {
          let {userInfo,token } =  res.data
          //登录成功
          // 1.提示登录成功
          this.$toast.success("登录成功")

          // 2.保存token和个人信息
          localStorage.setItem("token", token);
          localStorage.setItem("userInfo", JSON.stringify(userInfo));

          //3.登陆窗口隐藏并渲染信息
          setTimeout(() => {
            this.isShowLoginModel = false;
            this.avatarSrc = userInfo.avatar
            this.nickname = userInfo.nickname
            this.iconName = 'cross'

            // 如果是从其他页面强制过来就跳转回上一个页面。如果是在user页就不用
            // 所以要区别是不是强制过来user页面
            // isGoBack可能要多个组件用到，所以放在Vuex
            // if(是不是强制过来 isGoBack){
            //   // 1.如果isGoBack为true就要调回去
            //   // 2.开始就把isGoodBack设置为false， 强制登录(utils工具函数里面)再改为true
            //   // 3.跳转回去成功又要把他设置成false
            // }
            if(this.isGoBack){
              this.chanIsGoBack(false)
              this.$router.go(-1)
            }
            
          }, 500);
        } else {
          this.$toast(res.errmsg);
        }
      });
    },
    toShowLogoutModel(){
        // 跟提示语一样
        // 引入 Dialog 组件后，会自动在 Vue 的 prototype 上挂载 $dialog 方法，在所有组件内部都可以直接调用此方法。
        if(this.iconName=='cross'){
            this.$dialog.alert({
                title: '提示',
                message: '确认退出登录吗？',
                showCancelButton: true
            })
            .then(() => {
                // on confirm  点击确认
                // 1.提示
                this.$toast.success('退出登录成功')
                // 2.清除信息
                localStorage.removeItem('userInfo')
                localStorage.removeItem('token')
                // 3.页面值变为默认值
                this.avatarSrc = avatarSrc
                this.nickname = '点击登录'
                this.iconName = 'arrow'
            })
            .catch(() => {
                // on cancel  点击取消
            });
        }
    }
  },
};
</script>

<style lang='less' scoped>
.van-row {
  padding: 0.2rem 4%;
  background: #333;
  color: #fff;
  .van-col {
    line-height: 0.7rem;
    font-size: 0.16rem;
    img {
      width: 0.7rem;
      border-radius: 50%;
      display: block;
    }
    &:last-child {
      text-align: right;
    }
  }
}
.van-popup {
  width: 90%;
}
.van-grid-item{
    background-color: #fff;
    padding: 16px 8px;
}
</style>
